package com.bigdata.hdfs;

import cn.hutool.core.util.StrUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;

/**
 * @author xin.ding
 * @date 2020/10/27 15:08
 */
public class HdfsMain {
    private Configuration config = new Configuration();

    public Configuration getConfig() {
        return config;
    }

    public void initConf(String corePath, String sitePath, String hadoopHome, String userName) {
        config.addResource(corePath);
        config.addResource(sitePath);
        config.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
        if (StrUtil.isNotBlank(hadoopHome)) {
            System.setProperty("hadoop.home.dir", hadoopHome);
        }
        if (StrUtil.isNotBlank(userName)) {
            System.setProperty("HADOOP_USER_NAME", userName);
        }
    }

    public void buildKerberos(String krb5Path, String keytabPath, String principal) {
        System.setProperty("java.security.krb5.conf", krb5Path);
        // 配置认证方式
        config.set("hadoop.security.authentication", "Kerberos");
        config.set("keytab.file", keytabPath);
        UserGroupInformation.setConfiguration(config);
        try {
            UserGroupInformation.loginUserFromKeytab(principal, keytabPath);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
